import { Component, OnInit, Injector, ViewChild, Input } from '@angular/core';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import { Table } from 'primeng/table';
import { Paginator, LazyLoadEvent } from 'primeng/primeng';
import { PrimengTableHelper } from '@shared/helpers/PrimengTableHelper';
import {
    ListDtoExtensionsItem,
    Stock_BillListDto,
    StockZT_InventoryBillItemServiceProxy,
    Stock_InventoryItemListDto,
    StockType,
    StockZT_RoomServiceProxy
} from '@shared/service-proxies/stock-service-proxies';
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';
import { AppConsts } from '@shared/AppConsts';
import { HttpClient } from '@angular/common/http';
import { UserDataPermissionServiceProxy } from '@shared/service-proxies/stock-service-proxies';
import { FileDownloadService } from '@shared/utils/file-download.service';
import * as moment from 'moment';
@Component({
    templateUrl: './inventory-base.component.html',
    animations: [appModuleAnimation()],
    selector: 'inventory-base'
})
export class InventoryBaseComponent extends AppComponentBase implements OnInit {
    @ViewChild('dataTable') dataTable: Table;
    @ViewChild('paginator') paginator: Paginator;

    @ViewChild('detailDataTable') detailDataTable: Table;
    @ViewChild('detailPaginator') detailPaginator: Paginator;
    _stocktype: StockType;
    stocktypeString: string;
    @Input() set stocktype(val) {
        if (val) {
            this._stocktype = val;
            this.stocktypeString = val.toString();
        }
    }

    materialCodeFilter = '';
    f_InventBatchID = '';
    public dateRange: Date[] = [
        moment()
            .startOf('day')
            .toDate(),
        moment()
            .endOf('day')
            .toDate()
    ];
    billcode = '';

    extensions: Array<ListDtoExtensionsItem>;
    detialExtensions: Array<ListDtoExtensionsItem>;

    detailPrimengTableHelper: PrimengTableHelper;
    userDataPermissions;
    selectedBill: Stock_BillListDto;
    selectedBillItem = new Stock_InventoryItemListDto();
    billStatusOptions = [
        { label: '全部', value: undefined },
        { label: '新建', value: '新建' },
        { label: '已提交', value: '已提交' },
        { label: '已盘点', value: '已盘点' }
    ];
    billstatus = '';
    operatorOptions = [{ label: '当前登录人', value: undefined }, { label: '全部', value: '全部' }];
    operator = '';
    roomOption;
    selectedWareHouse;
    constructor(
        injector: Injector,
        private _fileDownloadService: FileDownloadService,
        private _billService: StockZT_InventoryBillItemServiceProxy,
        private _userDataPermissionServiceProxy: UserDataPermissionServiceProxy,
        private _stockZT_RoomServiceProxy: StockZT_RoomServiceProxy,
        private _httpClient: HttpClient
    ) {
        super(injector);
        this.detailPrimengTableHelper = new PrimengTableHelper();
    }
    ngOnInit(): void {
        if (this._stocktype.toString() == '市采') {
            this._userDataPermissionServiceProxy.getUserDataPermissions('Warehouses').subscribe(result => {
                this._stockZT_RoomServiceProxy.getRoomListByDepts(result.items, '市采物资库', '').subscribe(result2 => {
                    this.roomOption = result2.items.map(e => {
                        return {
                            label: e.displayText,
                            value: e
                        };
                    });
                    this.selectedWareHouse = result2.items;
                    this.getBills();
                });
            });
        } else if (this._stocktype.toString() == '军品') {
            this._userDataPermissionServiceProxy.getUserDataPermissions('Warehouses').subscribe(result => {
                this._stockZT_RoomServiceProxy.getRoomListByDepts(result.items, '原材料库', '').subscribe(result2 => {
                    this.roomOption = result2.items.map(e => {
                        return {
                            label: e.displayText,
                            value: e
                        };
                    });
                    this.selectedWareHouse = result2.items;
                    this.getBills();
                });
            });
        }

        this._userDataPermissionServiceProxy.getUserDataPermissions('Warehouses').subscribe(result => {
            this._stockZT_RoomServiceProxy.getRoomListByDepts(result.items, '工装库', '').subscribe(result2 => {
                this.roomOption = result2.items.map(e => {
                    return {
                        label: e.displayText,
                        value: e
                    };
                });
            });
            //先注释自动选中仓库 suocc
             this._stockZT_RoomServiceProxy.getRoomListByUserRole('工装库').subscribe(result2 => {
                 this.selectedWareHouse = result2.items;
                 this.getBills();
             });

        });
    }
    exportdata(id) {
        this.message.confirm('确认导出该条数据吗？', isConfirmed => {
            if (isConfirmed) {
                this.primengTableHelper.showLoadingIndicator();
                // let id = '401E0057-69FE-40A7-F4EB-08D716EF23C9';
                let uploadUrl = AppConsts.remoteServiceBaseUrl + '/File/ExportInventoryInfoToJson?billbaseIds=' + id;

                let isSuccessed = false;
                const formData: FormData = new FormData();
                this._httpClient
                    .post<any>(uploadUrl, formData)
                    .pipe(
                        finalize(() => {
                            this.primengTableHelper.hideLoadingIndicator();
                        })
                    )
                    .subscribe(response => {
                        if (response.error != null) {
                            this.message.error(this.l('导出失败,' + response.error.message));
                        } else {
                            isSuccessed = true;

                            if (response.result.fileName) {
                                this._fileDownloadService.downloadTempFile(response.result);
                                if (response.success) {
                                    this.notify.success('导出成功');
                                }
                            }
                        }
                    });
            }
        });
    }

    clearQuery() {
        this.materialCodeFilter = '';
        this.f_InventBatchID = '';
        this.billcode = '';
        this.userDataPermissions;
        this.billstatus = '';
        this.operator = '';
        this.roomOption;
    }
    getBills(event?: LazyLoadEvent) {
        if (!this.selectedWareHouse) {
            return;
        }
        if (this.primengTableHelper.shouldResetPaging(event) || event.first == undefined) {
            this.paginator.changePage(0);

            return;
        }

        this.primengTableHelper.showLoadingIndicator();
        this._billService
            .getInventoryBillListExtension(
                this.selectedWareHouse,
                this.materialCodeFilter,
                this.f_InventBatchID,
                this.billcode,
                this.billstatus,
                this.operator,
                moment(this.dateRange[0]),
                moment(this.dateRange[1]),
                this._stocktype,
                this.primengTableHelper.getSorting(this.dataTable),
                this.primengTableHelper.getMaxResultCount(this.paginator, event),
                this.primengTableHelper.getSkipCount(this.paginator, event)
            )
            .subscribe(result => {
                this.extensions = result.items;
                this.primengTableHelper.totalRecordsCount = result.dtos.totalCount;
                this.primengTableHelper.records = result.dtos.items;
                this.primengTableHelper.hideLoadingIndicator();

                this.detailPrimengTableHelper.totalRecordsCount = 0;
                this.detailPrimengTableHelper.records = null;

                this.selectedBill = null;
                this.selectedBillItem = null;
            });
    }

    printBillList() {
        if (this.selectedBill === null || this.selectedBill.id === undefined) {
            this.notify.error('请选择需要打印的单据！');
        } else {
            if (this._stocktype == StockType.军品) {
                window.open(
                    AppConsts.printAddr + '/webroot/decision/view/report?viewlet=erp/XHWPDHZ.cpt&BillId=' +
                        this.selectedBill.id
                );
            }
            if (this._stocktype == StockType.市采) {
                window.open(
                    AppConsts.printAddr + '/webroot/decision/view/report?viewlet=erp/SCWPDHZ.cpt&BillId=' +
                        this.selectedBill.id
                );
            }
        }
    }
    submitBill() {
        if (!this.selectedBill) {
            return;
        }

        this.message.confirm('确认提交该条数据吗？', isConfirmed => {
            if (isConfirmed) {
                this.primengTableHelper.showLoadingIndicator();
                this._billService
                    .submitInventoryBillBase(this.selectedBill.id)
                    .pipe(
                        finalize(() => {
                            this.primengTableHelper.hideLoadingIndicator();
                        })
                    )
                    .subscribe(() => {
                        this.notify.success(this.l('更新成功'));
                        this.getBills();
                        this.primengTableHelper.hideLoadingIndicator();
                    });
            }
        });
    }
    postBill() {
        if (!this.selectedBill) {
            return;
        }
        this.message.confirm('确认过账该条数据吗？', isConfirmed => {
            if (isConfirmed) {
                this.primengTableHelper.showLoadingIndicator();
                this._billService
                    .postInventoryBillBase(this.selectedBill.id)
                    .pipe(
                        finalize(() => {
                            this.primengTableHelper.hideLoadingIndicator();
                        })
                    )
                    .subscribe(() => {
                        this.notify.success(this.l('更新成功'));
                        this.getBills();
                        this.primengTableHelper.hideLoadingIndicator();
                    });
            }
        });
    }
    sendBackBill() {
        if (!this.selectedBill) {
            return;
        }

        this.message.confirm('确认退回该条数据吗？', isConfirmed => {
            if (isConfirmed) {
                this.primengTableHelper.showLoadingIndicator();
                this._billService
                    .sendBackInventoryBillBase(this.selectedBill.id)
                    .pipe(
                        finalize(() => {
                            this.primengTableHelper.hideLoadingIndicator();
                        })
                    )
                    .subscribe(() => {
                        this.notify.success(this.l('更新成功'));
                        this.getBills();
                        this.primengTableHelper.hideLoadingIndicator();
                    });
            }
        });
    }

    reloadData(event) {
        if (event == null || event == undefined) {
            this.getBills();
        } else {
            this.getBillItems();
        }
    }
    getBillItems(event?: LazyLoadEvent) {
        if (!this.selectedBill) {
            return;
        }
        if (this.detailPrimengTableHelper.shouldResetPaging(event)) {
            this.detailPaginator.changePage(0);

            return;
        }

        this.primengTableHelper.showLoadingIndicator();

        this._billService
            .getInventoryBillItemListExtension(
                this.selectedBill.id,
                this.detailPrimengTableHelper.getSorting(this.detailDataTable),
                this.detailPrimengTableHelper.getMaxResultCount(this.detailPaginator, event),
                this.detailPrimengTableHelper.getSkipCount(this.detailPaginator, event)
            )
            .subscribe(result => {
                this.detialExtensions = result.items;
                this.detailPrimengTableHelper.totalRecordsCount = result.dtos.totalCount;
                this.detailPrimengTableHelper.records = result.dtos.items;
                this.primengTableHelper.hideLoadingIndicator();
                this.selectedBillItem = null;
            });
    }

    deleteBill() {
        if (!this.selectedBill) {
            return;
        }

        this.message.confirm('确认删除该条数据吗？', isConfirmed => {
            if (isConfirmed) {
                this.primengTableHelper.showLoadingIndicator();
                this._billService
                    .deleteInventoryBillBase(this.selectedBill.id)
                    .pipe(
                        finalize(() => {
                            this.primengTableHelper.hideLoadingIndicator();
                        })
                    )
                    .subscribe(() => {
                        this.notify.success(this.l('SuccessfullyDeleted'));
                        this.getBills();
                        this.primengTableHelper.hideLoadingIndicator();
                    });
            }
        });
    }

    deleteBillItem() {
        if (!this.selectedBillItem) {
            return;
        }

        this.message.confirm('确认删除该条数据吗？', isConfirmed => {
            if (isConfirmed) {
                this.primengTableHelper.showLoadingIndicator();
                this._billService
                    .deleteInventoryBillItem(this.selectedBillItem.id)
                    .pipe(
                        finalize(() => {
                            this.primengTableHelper.hideLoadingIndicator();
                        })
                    )
                    .subscribe(() => {
                        this.notify.success(this.l('SuccessfullyDeleted'));
                        this.getBillItems();
                        this.primengTableHelper.hideLoadingIndicator();
                    });
            }
        });
    }
}
